package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SetmealDishService setmealDishService;
    @Override
    public Page<SetmealDto> pageSetmealDto(Integer page, Integer pageSize, String name) {
        Page<SetmealDto> pageInfo = new Page<>(page, pageSize);
        return setmealMapper.pageSetmealDto(pageInfo, name);
    }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
        return setmealMapper.getByIdWithDish(id);
    }

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1. 保存套餐数据，操作setmeal表，添加一条数据
        this.save(setmealDto);
        //2. 保存套餐数据，操作setmeal_dish，添加多条数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void updateWithDishs(SetmealDto setmealDto) {
        updateById(setmealDto);
        //删除原菜品
        setmealDishService.update().eq("setmeal_id", setmealDto.getId()).remove();
        //添加新菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void deleteByIds(Long[] ids) {
        Integer count1 = query().in("id", Arrays.asList(ids)).eq("status", 1).count();
        if (count1 > 0) {
            throw new CustomerException("有套餐正在售卖，不能删除");
        }
        removeByIds( Arrays.asList(ids));
        setmealDishService.update()
                .in("setmeal_id",Arrays.asList(ids))
                .remove();
    }
}
